import React from 'react';
import { FormPanel, ExtendReader, type FormPanelObject, FormPanelStatus, InputType } from 'lfun-bg-comp';
import { Card, Button, Table, Space, Modal, Cascader, TableProps, message } from 'antd';
import { useLocation } from 'react-router';
import _ from 'lodash';
import { GENDER, YES_NO } from '@/constant/basicOptions';
import {
  ID_TYPE,
  RELATION,
  POLITICAL_STATUS,
  FAMILY_MEMBER_OCCUPATION,
  HEALTH_CONDITION,
} from '@/constant/studentOptions';
import { ETHNICITIES } from '@/constant/ethnicity';
import { countries } from '@/constant/country';
import { GraduationyeaInfo, create, search, update, del } from '@/service/student/family';
import { isPermissionOperate } from '@/component/permission-button';

// const mockvalue = [
//   {
//     name: '张开',
//     gender: '男',
//     relationship: '父子',
//     isGuardian: '是',
//     idType: '居民身份证',
//     idNumber: '371122********3222',
//     phone: '184****7123',
//     ethnicity: '汉',
//   },
//   {
//     name: '严*民',
//     gender: '女',
//     relationship: '母子',
//     isGuardian: '是',
//     idType: '居民身份证',
//     idNumber: '371122********5435',
//     phone: '135****6488',
//     ethnicity: '汉',
//   },
//   {
//     name: '张利',
//     gender: '男',
//     relationship: '兄弟',
//     isGuardian: '否',
//     idType: '居民身份证',
//     idNumber: '371122********3223',
//     phone: '181****4636',
//     ethnicity: '汉',
//   },
// ];

type TFormModel = {
  visible: boolean;
  onCancel: () => void;
  onSave: () => void;
  isEdit: string;
  value: any;
  // formData?: any;
};

const FormModal: React.FC<TFormModel> = ({ visible, onCancel, onSave, isEdit, value }) => {
  const [form, setForm] = React.useState<any>();
  const location = useLocation();
  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      inputs: [
        {
          label: '国籍/地区',
          name: 'nationality',
          key: 'nationality',
          inputType: InputType.select,
          renderOption: countries,
        },
        {
          label: '成员姓名',
          name: 'name',
          key: 'name',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '性别',
          name: 'gender',
          key: 'gender',
          required: true,
          inputType: InputType.select,
          renderOption: GENDER,
          render: (formObjectPanel: FormPanelObject) => {
            const id_type = form.getFieldValue('identification_type');
            if (id_type !== 'resident_id_card') {
              return form.getFieldValue('gender');
            }
            return ExtendReader.renderGender('identification_type', 'gender', formObjectPanel);
          },
        },
        {
          label: '关系',
          name: 'relationship',
          key: 'relationship',
          required: true,
          inputType: InputType.select,
          renderOption: RELATION,
        },
        {
          label: '是否监护人',
          name: 'is_guardian',
          key: 'is_guardian',
          required: true,
          inputType: InputType.select,
          renderOption: YES_NO,
        },
        {
          label: '身份证类型',
          name: 'identification_type',
          key: 'identification_type',
          relationFields: ['identification_number'],
          required: true,
          inputType: InputType.select,
          renderOption: ID_TYPE,
        },
        {
          label: '身份证号码',
          name: 'identification_number',
          key: 'identification_number',
          relationFields: ['birthday', 'gender'],
          required: true,
          textRange: [0, 30],
          ruleType: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('identification_type');
            if (id_type === 'resident_id_card') {
              return 'cnPeopleNo';
            }
            return '';
          },
          renderValidate: (formOjbectPanel: FormPanelObject) => {
            const id_type = formOjbectPanel.getFieldValue('identification_type');
            if (id_type === 'resident_id_card') {
              return ExtendReader.validateCnPeopleNo(
                formOjbectPanel.getFieldValue('identification_number'),
                formOjbectPanel.getFieldValue('birthday'),
                formOjbectPanel.getFieldValue('gender')
              );
            }
            return '';
          },
        },
        {
          label: '出生年月',
          name: 'birthday',
          key: 'birthday',
          required: true,
          inputType: InputType.date,
          render: (formObjectPanel: FormPanelObject) => {
            const id_type = form.getFieldValue('identification_type');
            if (id_type !== 'resident_id_card') {
              return form.getFieldValue('birthday');
            }
            return ExtendReader.renderBirthday('identification_number', 'birthday', formObjectPanel);
          },
        },
        {
          label: '手机号码',
          name: 'phone_number',
          key: 'phone_number',
          required: true,
          ruleType: 'cnPhone',
        },
        {
          label: '民族',
          name: 'ethnicity',
          key: 'ethnicity',
          required: true,
          inputType: InputType.select,
          renderOption: ETHNICITIES,
        },
        {
          label: '健康状况',
          name: 'health_status',
          key: 'health_status',
          inputType: InputType.cascader,
          renderOption: HEALTH_CONDITION,
        },
        {
          label: '政治面貌',
          name: 'political_status',
          key: 'political_status',
          required: false,
          inputType: InputType.select,
          renderOption: POLITICAL_STATUS,
        },
        {
          label: '国籍',
          name: 'nationality',
          key: 'nationality',
          required: true,
          inputType: InputType.select,
          renderOption: countries,
        },
        {
          label: '联系地址',
          name: 'contact_address',
          key: 'contact_address',
          required: true,
        },
        {
          label: '工作单位',
          name: 'workplace',
          key: 'workplace',
          textRange: [0, 50],
        },
        {
          label: '家庭成员职业',
          name: 'family_member_occupation',
          key: 'family_member_occupation',
          inputType: InputType.children,
          children: <Cascader />,
          renderOption: FAMILY_MEMBER_OCCUPATION,
        },
      ],
    },
  ];
  const handleSave = () => {
    onSave();
  };

  React.useEffect(() => {
    form?.resetFields();
  }, [value]);

  return (
    <Modal
      title={isEdit === 'edit' ? '编辑成员' : '添加成员'}
      width="80%"
      footer={[]}
      open={visible}
      onOk={handleSave}
      onCancel={onCancel}
    >
      <FormPanel
        btnsAlign="center"
        restBtnText="返回"
        submitBtnText="确定"
        buttonsDisplay="block"
        onLoad={form => {
          setForm(form);
        }}
        values={value}
        formStatus={isEdit !== 'view' ? FormPanelStatus.edit : FormPanelStatus.nonEdit}
        onReset={onCancel}
        onFinish={async (formObjectPanel: FormPanelObject) => {
          const values = formObjectPanel.getFieldsValue();
          if (isEdit === 'add') {
            const createValue: GraduationyeaInfo = {
              ...values,
              student_id: location.state.student_id,
              birthday: values?.birthday?.format('YYYY-MM-DD'),
              family_member_occupation: values?.family_member_occupation?.join(','),
            };
            const res = await create(createValue);
            if (res.success) {
              message.success('添加成功');
              form.resetFields();
              onSave();
            } else {
              formObjectPanel.reVaildation(res);
            }
          } else if (isEdit === 'edit') {
            const upValue: GraduationyeaInfo = {
              ...value,
              ...values,
              student_id: location.state.student_id,
              birthday: values?.birthday?.format('YYYY-MM-DD'),
              family_member_occupation: values?.family_member_occupation?.join(','),
            };
            const res = await update(upValue);
            if (res.success) {
              message.success('编辑成功');
              form.resetFields();
              onSave();
            } else {
              formObjectPanel.reVaildation(res);
            }
          }
        }}
        template={list}
      />
    </Modal>
  );
};

const Family: React.FC = () => {
  const location = useLocation();
  const [value, setValue] = React.useState([]);
  const [cur, setCur] = React.useState<any>({});

  const init = async () => {
    setLoading(true);
    const res: any = await search(location.state.student_id);
    if (res.success) {
      setValue(res.data);
    }
    setLoading(false);
  };
  React.useEffect(() => {
    init();
  }, []);

  const columns: TableProps['columns'] = [
    {
      title: '成员姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: v => {
        return _.find(GENDER, { value: v })?.label;
      },
    },
    {
      title: '关系',
      dataIndex: 'relationship',
      key: 'relationship',
      render: v => {
        return _.find(RELATION, { value: v })?.label;
      },
    },
    {
      title: '是否监护人',
      dataIndex: 'is_guardian',
      key: 'is_guardian',
      render: v => {
        return _.find(YES_NO, { value: v })?.label;
      },
    },
    {
      title: '身份证件类型',
      dataIndex: 'identification_type',
      key: 'identification_type',
      render: v => {
        return _.find(ID_TYPE, { value: v })?.label;
      },
    },
    {
      title: '证件号码',
      dataIndex: 'identification_number',
      key: 'identification_number',
    },
    {
      title: '手机号',
      dataIndex: 'phone_number',
      key: 'phone_number',
    },
    {
      title: '民族',
      dataIndex: 'ethnicity',
      key: 'ethnicity',
      render: v => {
        return _.find(ETHNICITIES, { value: v })?.label;
      },
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            查看
          </Button>
          {!location.pathname.includes('/details/') ? (
            <>
              <Button type="link" onClick={() => handleFormModel('edit', record)}>
                编辑
              </Button>
              <Button type="link" onClick={() => handleDelete(record)}>
                删除
              </Button>
            </>
          ) : null}
        </Space>
      ),
    },
  ];

  const isAddBtn = () => {
    return !location.pathname.includes('details');
  };
  //
  const [openModel, setOpenModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState('');
  const [showDelModel, setShowDelModel] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  const handleDelete = (record: any) => {
    setCur(record);
    setShowDelModel(true);
  };

  const handleDelConfirm = async () => {
    const res = await del(cur.student_family_info_id);
    if (res.success) {
      message.success('删除成功');
      init();
      setShowDelModel(false);
    }
  };

  const handleFormModel = (type, record: any = {}) => {
    if (type === 'edit') {
      const r = { ...record, family_member_occupation: record.family_member_occupation?.split(',') };
      setCur(r);
      setIsEdit('edit');
    } else if (type === 'add') {
      setCur({});
      setIsEdit('add');
    } else {
      setIsEdit('view');
    }
    setOpenModel(true);
  };

  const handleView = val => {
    const r = { ...val, family_member_occupation: val.family_member_occupation?.split(',') };
    setCur(r);
    setIsEdit('view');
    setOpenModel(true);
  };
  return (
    <Card>
      {isAddBtn() && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={() => handleFormModel('add')}>
          新增家庭成员
        </Button>
      )}
      <FormModal
        value={cur}
        visible={openModel}
        onCancel={() => setOpenModel(false)}
        onSave={() => {
          init();
          setOpenModel(false);
        }}
        isEdit={isEdit}
      />
      <Table scroll={{ x: 'max-content' }} loading={loading} dataSource={value} columns={columns} pagination={false} />
      <FormPanel
        value={cur}
        visible={openModel}
        onCancel={() => setOpenModel(false)}
        onSave={() => {
          init();
          setOpenModel(false);
        }}
        isEdit={isEdit}
      />
      <Modal
        title="删除"
        width="40%"
        open={showDelModel}
        onOk={handleDelConfirm}
        onCancel={() => setShowDelModel(false)}
      >
        {`家庭成员: ${cur.name} 是否删除?`}
      </Modal>
    </Card>
  );
};

export default Family;
